import base64
import pymysql.cursors
import logging
import uuid
from datetime import datetime
import json
from flask import request,jsonify
from .alarm_data import add
from .normal_data import add as normal_datas
from configparser import ConfigParser
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb
def shi_cheng_dian_qi():
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = json.loads(request.data)
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        data = '"'+str(jsons)+'"'
        sql = "insert into all_data (data,date_time,type) values(%s,'%s','%s')" %(data,creation_date,'shi_cheng_water')
        insert = cursor.execute(sql)
        mydb.commit()
        cursor.close()  # 关闭游标
        if jsons.__contains__('payload'):
            APPdata = jsons.get('payload').get('APPdata')
            data = base64.b64decode(APPdata).decode(encoding ='utf-8',errors = 'strict')
            # 液位、液压表示
            flag = data[6:9]
            # 设备号
            number = data[9:24]
            # 当前值
            currentValue = data[34:38]
            # 时间
            time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            kpaOrM = ""
            if currentValue[0:4] == "0000":
                kpaOrM = "0"
            elif currentValue[0:3] == "000":
                kpaOrM = currentValue[3:4]
            elif currentValue[0:3] == "00":
                kpaOrM = currentValue[2:4]
            elif currentValue[0:3] == "0":
                kpaOrM = currentValue[1:4]
            else:
                kpaOrM = currentValue
            # 报警类型
            alarmTypeName = ""
            alarmType = ""
            # 报警内容
            content = ""
            # 报警表示
            alarmFlag = False
            # 报警数据
            json_alarm_data = {}
            # 正常数据
            json_normal_data = {}
            json_normal_data_arr = []
            normal_data = {}
            data_float = 0
            if flag == "902":
                data_float = float(kpaOrM) / 1000
                if data_float > 0.5 or data_float < 0.1:
                    alarmFlag = True
                    alarmTypeName = "水压报警"
                    alarmType = "001e7548-8735-4b31-b30b-c9361a62c923"
                    content = "水压报警 " + "报警值:" + str(data_float) + "MPa"
                normal_data['name'] = '水压'
                normal_data['value'] = data_float
                json_normal_data_arr.append(normal_data)
            else:
                data_float = float(kpaOrM) / 100
                if data_float > 0.5 or data_float < 0.1:
                    alarmFlag = True
                    alarmTypeName = "水位报警"
                    alarmType = "001e7548-8735-4b31-b30b-c9361a62c924"
                    content = "水位报警 " + "报警值:" + str(data_float) + "m"
                normal_data['name'] = '当前水位'
                normal_data['value'] = data_float
                json_normal_data_arr.append(normal_data)
            if alarmFlag:
                json_alarm_data['number'] = number
                json_alarm_data['alarmType'] = alarmType
                json_alarm_data['alarmTypeName'] = alarmTypeName
                json_alarm_data['content'] = content
                json_alarm_data['alarmTime'] = time
                json_alarm_data['dataType'] = 'alarm'
                add(json_alarm_data)
            json_normal_data['number'] = number
            json_normal_data['paramInfo'] = json_normal_data_arr
            json_normal_data['time'] = time
            json_normal_data['type'] = 'water'
            json_normal_data['dataType'] = 'normal'
            normal_datas(json_normal_data)
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg = "success",
        code = 0
    )
